<template>
	<div>
		<div class="container">
			<h2 style="text-align: center;">验收单</h2>
			<div class="toolbar mt-2">
				<a-form ref="searchRef" layout="inline" :label-col="{style: { width: '100px' }}" :model="searchState" @finish="current=1;loading=true;initData()">
					<a-row :gutter="20">
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" allow-clear @change="changeProject"></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="选择供应商名称" name="supplier_id">
								<a-select v-model:value="searchState.supplier_id" :show-search="true" placeholder="请选择供应商" :options="userlist" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="验收类型" name="ys_type">
								<a-select v-model:value="searchState.ys_type" :show-search="true" placeholder="请选择验收类型" :options="typeOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="采购单编号">
								<a-input v-model:value="searchState.purchase_order_code" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<!--
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="状态" name="ys_status" :rules="{required:true, message:'请选择验收状态'}">
								<a-radio-group v-model:value="searchState.ys_status">
									<a-radio :value="1">未验收</a-radio>
									<a-radio :value="2">已验收</a-radio>
								</a-radio-group>
							</a-form-item>
						</a-col>-->
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="发货单编号">
								<a-input v-model:value="searchState.code" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8">
							<a-form-item label="时间范围">
								<a-range-picker v-model:value="searchState.date_range" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
							</a-form-item>
						</a-col>
						<a-col :span="8" style="padding: 15px 0;">
							<a-radio-group v-model:value="searchState.date_type" style="margin-left: 20px;" @change="setDatetype">
								<a-radio :value="1">上周</a-radio>
								<a-radio :value="2">上月</a-radio>
								<a-radio :value="3">本周</a-radio>
								<a-radio :value="4">本月</a-radio>
							</a-radio-group>
						</a-col>
						<a-col :span="8" style="padding: 10px 0;">
							<a-form-item label="选择验收人" name="opr_id">
								<a-select v-model:value="searchState.opr_id" :show-search="true" placeholder="请选择验收人" :options="oprlist" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="4">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
				v-if="!loading"使得:default-expand-all-rows="true"生效
				-->
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="yanshouSource" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'project'">
							<a-tag v-if="record.is_weighbridge === 1" color="red">地磅</a-tag>
							{{ record.project?.name || '' }}
						</template>
						<template v-if="column.key === 'ys_status'">
							<a-button v-if="record.ys_status===1 && record.ys_settings.filter(item => item.ys_status === 2).length" size="small">验收中</a-button>
							<a-button v-if="record.ys_status===1 && !record.ys_settings.filter(item => item.ys_status === 2).length" danger size="small">未验收</a-button>
							<a-button v-if="record.ys_status===2" disabled size="small">已验收</a-button>
						</template>
						<template v-if="column.key === 'ys_setting'">
							<!--							<a-button v-if="record.ys_settings.length" v-permission:show="219" size="small" type="primary" ghost @click="ysSetting(record)">查看</a-button>-->
							<!--							<a-button v-else v-permission:show="220" size="small" @click="ysSetting(record)">未设置</a-button>-->
							<a-button v-if="record.ys_settings.length" size="small" type="primary" ghost @click="ysSetting(record)">查看</a-button>
							<a-button v-else size="small" @click="ysSetting(record)">未设置</a-button>
						</template>
						<template v-else-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="71" @click="show(record)">
									查看
								</a-button>
								<a-button
									v-if="
										record.ys_status === 1 &&
											(record.ys_settings.find(item => item.opr_id === userInfo.id && item.ys_status === 1 && item.opr_type === 1) ||
												(
													record.ys_settings.find(item => item.opr_id === userInfo.id && item.ys_status === 1 && item.opr_type === 0)
													&& record.ys_settings.find(item => item.ys_status === 2 && item.opr_type === 1)
												))
									"
									v-permission="70"
									type="primary"
									danger
									@click="edit(record)">去验收</a-button>
							</a-space>
						</template>
					</template>
				</a-table>
			</div>
			<a-modal v-model:visible="visible" title="验收设置(验收人不得低于3人)" :mask-closable="false" width="600px">
				<a-steps direction="vertical" :current="currentStep" class="steps">
					<a-step title="主验收人">
						<template #description>
							<div>
								<a-space>
									<a-typography-text>
										<!-- 如果为小于等于0 是未验收 给用户显示选择验收人 -->
										<a-select v-if="currentStep <= 0" v-model:value="modalState.main_opr_id" :show-search="true" :options="mainYsOprList" type="small" placeholder="请选择验收人" option-filter-prop="label" allow-clear />
										<a-space v-else>
											<div v-for="(item, index) in modalState.record.ys_settings" :key="index">
												<a-space v-if="item.opr_type === 1">
													<a-typography-text v-if="item.ys_status === 2" type="secondary">{{ item.update_time }}</a-typography-text>
													<a-typography-text>{{ mainYsOprList.find(i => i.value === item.opr_id)?.label }}</a-typography-text>
													<a-typography-text v-if="item.ys_status === 2" type="success">已验收</a-typography-text>
													<a-typography-text v-else type="secondary">待验收</a-typography-text>
												</a-space>
											</div>
										</a-space>
									</a-typography-text>
								</a-space>
							</div>
						</template>
					</a-step>
					<a-step title="共同验收人">
						<template #description>
							<div>
								<!-- currentStep如果为小于等于0 是未验收 给用户显示选择验收人 disabled大于0表示3人中已经有人验收 -->
								<a-space v-if="currentStep <= 0">
									<a-typography-text>
										<a-select v-model:value="modalState.jointly_opr_ids" :show-search="true" style="min-width: 112px" mode="multiple" :options="jointlyYsOprList" type="small" placeholder="请选择共同验收人" option-filter-prop="label" allow-clear :disabled="currentStep > 0" />
									</a-typography-text>
								</a-space>
								<template v-else>
									<template v-for="(item, index) in modalState.record.ys_settings" :key="index">
										<div>
											<a-space v-if="item.opr_type === 0">
												<a-typography-text v-if="item.ys_status === 2" type="secondary">{{ item.update_time }}</a-typography-text>
												<a-typography-text>{{ jointlyYsOprList.find(i => i.value === item.opr_id)?.label }}</a-typography-text>
												<a-typography-text v-if="item.ys_status === 2" type="success">已验收</a-typography-text>
												<a-typography-text v-else type="secondary">待验收</a-typography-text>
											</a-space>
										</div>
									</template>
								</template>
							</div>
						</template>
					</a-step>
					<a-step title="验收完成">
					</a-step>
				</a-steps>
				<template #footer>
					<a-space>
						<a-button @click="visible = false">关闭</a-button>
						<!-- <a-button v-if="modalState.record.ys_status === 1 && !modalState.record.ys_settings.filter((item) => item.ys_status === 2).length" v-permission="220" type="primary" @click="saveYsSetting">提交</a-button>-->
						<a-button v-if="modalState.record.ys_status === 1 && !modalState.record.ys_settings.filter((item) => item.ys_status === 2).length" type="primary" @click="saveYsSetting">提交</a-button>
					</a-space>
				</template>
			</a-modal>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";

const { proxy } = getCurrentInstance();

import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, RightOutlined } from "@ant-design/icons-vue";

import { post, postJson } from "../utils";

import { usePagination } from "vue-request";
import { userStore } from "@/store/index.js";
import { Result } from "ant-design-vue";

const searchRef = ref();
const searchState = reactive({});
const projectOptions = ref([]);
const planlist = ref([]);
const contractlist = ref([]);
const userlist = ref([]); //供应商列表
const oprlist = ref([]); //操作人列表
const store = userStore();
const userInfo = store.info;
const route = useRoute();
const router = useRouter();
const query = route.query;
const typeOptions = [
	{ value: 0, label: "请选择" },
	{ value: 1, label: "钢筋" },
	{ value: 2, label: "混凝土" },
	{ value: 3, label: "周转材料" },
	{ value: 4, label: "机械" },
	{ value: 5, label: "其它" },
	{ value: 6, label: "辅助材料" }
];
const statusOptions = [
	{
		value: 1,
		label: "待验收"
	},
	{
		value: 2,
		label: "已验收"
	}
];

const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 100,
		align: "left",
		fixed: "left"
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
	},
	{
		title: "供应商名称",
		dataIndex: "supplier",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return text.company_name;
		}
	},
	{
		title: "采购单名称",
		dataIndex: "purchaseOrder",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.code;
		}
	},
	{
		title: "发货单编号",
		dataIndex: "code",
		sorter: false,
		width: 150,
		ellipsis: true
	},
	{
		title: "采购人",
		dataIndex: "purchaseOrder",
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.purchaser.fullname || text.purchaser.username;
		}
	},
	// {
	// 	title: "验收类型",
	// 	dataIndex: "purchaseOrder",
	// 	width: 150,
	// 	ellipsis: true,
	// 	customRender: ({ text, record, index, column }) => {
	// 		return text.type === "purchase" ? "主要物资" : text.type === "shangtong" ? "商砼预约" : "机械申请";
	// 	}
	{
		title: "验收类型",
		dataIndex: "ys_type",
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return typeOptions.filter(typeOption => typeOption.value === text)?.[0]?.label || "";
		}
	},
	{
		title: "状态",
		dataIndex: "ys_status",
		key: "ys_status",
		sorter: false,
		width: 150,
		align: "center"
	},
	{
		title: "验收设置",
		dataIndex: "ys_setting",
		key: "ys_setting",
		sorter: false,
		fixed: "right",
		width: 100,
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 280,
		align: "center"
	}
];
const visible = ref(false);
const modalState = ref({});
const projectOprList = ref([]);
const projectConsignorList = ref([]);
const currentStep = ref(0);
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));

const { data, loading, run, current, pageSize, total } = usePagination(params => post("supplyOrder", { ys_status: 1, ship_status: 2, exit_time: 1, ...params, ...searchState }), {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

const yanshouSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters,
		start_time: searchState.date_range && searchState.date_range[0],
		end_time: searchState.date_range && searchState.date_range[1],
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.supplier_id) searchState.supplier_id = parseInt(query.supplier_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.ys_type) searchState.ys_type = parseInt(query.ys_type);
	if (query.purchase_order_code) searchState.purchase_order_code = query.purchase_order_code;
	if (query.code) searchState.code = query.code;
	if (query.start_time && query.end_time) {
		searchState.date_range = [
			dayjs(query.start_time).format('YYYY-MM-DD HH:mm:ss'),
			dayjs(query.end_time).format('YYYY-MM-DD HH:mm:ss')
		];
	}
	
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	if (query.opr_id) searchState.opr_id = parseInt(query.opr_id);
	initData(pag);
}
post("department/projects?type=3").then(({ data }) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("plan", { type: 1 }).then(({ data }) => {
	planlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("contract", { type: 1 }).then(({ data }) => {
	contractlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
post("user", { is_supplier: 1, page_size: Infinity }).then(({ data }) => {
	userlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.company_name
		};
	});
});
post("user", { page_size: Infinity }).then(({ data }) => {
	oprlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.fullname
		};
	});
});
const changeProject = value => {
	const project_id = value;
	post("plan", { type: 1, project_id: project_id, page_size: 1000 }).then(({ data }) => {
		planlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
	});
};
const changePlan = value => {
	const plan_id = value;
	post("contract", { plan_id: plan_id, page_size: 1000 }).then(({ data }) => {
		contractlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
	});
};
const ysSetting = async (record) => {
	visible.value = true;
	modalState.value = {
		main_opr_id: null,
		jointly_opr_ids: [],
		record,
	};

	const projectUser = await post("project/user", { project_id: record.project_id, scene: 'main', status: '1' });
	projectOprList.value = projectUser.map(d => {
		return {
			value: d.id,
			label: d.fullname,
		}
	})
	// 共同验收人列表
	const userReusult = await post("user/ys", { opr_type: 0, project_id: record.project_id });
	projectConsignorList.value = userReusult.map(d => {
		const consignorOpt = d.departments[0]?.UserDepartment || {};
		const _day = dayjs().format('YYYY-MM-DD');
		// is_permanent 1永久 !=1时效
		const disabled = !consignorOpt.is_permanent && (_day > consignorOpt.end_validity || _day < consignorOpt.start_validity);
		return {
			value: d.id,
			label: d.fullname + (d.is_consignor ? '(委托人)' : ''),
			disabled,
			is_consignor: d.is_consignor,
		}
	}).filter((item) => !item.disabled); // 过滤处理小程序
	currentStep.value = record.ys_status === 2 ? 3 : 0;
	// 如果验收人列表有值就循环把验收类型为1的值给到主验收人默认展示数据，否则就是共同验收人默认展示数据
	if (record.ys_settings?.length) {
		for (const ys_setting of record.ys_settings) {
			if (ys_setting.opr_type === 1) {
				modalState.value.main_opr_id = ys_setting.opr_id;
			} else {
				modalState.value.jointly_opr_ids.push(ys_setting.opr_id);
			}
			// 如果验收状态为已验收(2)并且验收人数小于1的话就把验收人数++ （最初的数据没有验收人数就要加，处理老数据）
			if (ys_setting.ys_status === 2 && currentStep.value < 1) {
				currentStep.value++;
			}
		}
	} else if (record.receiver_id) { // receiver_id 如果签收人id存在的话，就吧主验收人设置为列表传来的值
		const user = projectOprList.value.find(item => item.value === record.receiver_id);
		modalState.value.main_opr_id = user?.value || null;
	} else { // 如果receiver_id为空，就取receiver（处理更旧的数据）
		const user = projectOprList.value.find(item => item.label === record.receiver);
		modalState.value.main_opr_id = user?.value || null;
	}
}
const mainYsOprList = computed(() => {
	if (modalState.value.jointly_opr_ids.length) {
		return JSON.parse(JSON.stringify(projectOprList.value)).map((item) => {
			if (modalState.value.jointly_opr_ids.includes(item.value)) {
				item.disabled = true;
			}
			return item;
		})
	} else {
		return projectOprList.value;
	}
})
const jointlyYsOprList = computed(() => {
	const listMap = {};
	for (const item of projectOprList.value) {
		listMap[item.value] = item;
	}
	for (const item of projectConsignorList.value) {
		listMap[item.value] = item;
	}
	const list = Object.values(listMap);
	if (modalState.value.main_opr_id) {
		return JSON.parse(JSON.stringify(list)).map((item) => {
			if (modalState.value.main_opr_id === item.value) {
				item.disabled = true;
			}
			return item;
		})
	} else {
		return list;
	}
})

const saveYsSetting = () => {
	if (!modalState.value.main_opr_id) return proxy.$message.error("请选择主验收人");
	if (modalState.value.jointly_opr_ids.length < 2) return proxy.$message.error("共同验收人不得少于2人");
	// 如果已选共同验收人里面没有委托人的话提示“共同验收人必须要选一个委托人”(主要合同)
	// modalState.jointly_opr_ids 已选的共同验收人
	// jointlyYsOprList.value 共同验收人列表
	if ([1, 2, 5].includes(modalState.value.record?.ys_type)) {
		const result = modalState.value.jointly_opr_ids.some(i => {
			const result = jointlyYsOprList.value.find(j => j.value === i)
			return result && result.is_consignor === 1
		})

		if (!result) {
			return proxy.$message.error("共同验收人需一个分包单位授权领料人或法人");
			// return proxy.$confirm({
			// 	title: '警告',
			// 	content: '您选择的共同验收人中没有委托人，是否继续？',
			// 	onOk: () => {
			// 		postJson("ysSetting/save", {
			// 			main_opr_id: modalState.value.main_opr_id,
			// 			jointly_opr_ids: modalState.value.jointly_opr_ids,
			// 			supply_order_id: modalState.value.record.id
			// 		}).then(() => {
			// 			proxy.$message.success("更新成功", 1);
			// 			visible.value = false;
			// 			initData()
			// 		})
			// 			.catch(err => {
			// 				proxy.$message.error(err);
			// 			});
			// 	},
			// 	onCancel() {
			// 		return;
			// 	},
			// })
		}
	}

	postJson("ysSetting/save", {
		main_opr_id: modalState.value.main_opr_id,
		jointly_opr_ids: modalState.value.jointly_opr_ids,
		supply_order_id: modalState.value.record.id
	}).then(() => {
		proxy.$message.success("更新成功", 1);
		visible.value = false;
		initData()
	})
		.catch(err => {
			proxy.$message.error(err);
		});
};
const edit = ({ id }) => {
	router.push(`/yanshou/edit/${id}`);
};
const show = ({ id }) => {
	router.push(`/yanshou/info/${id}`);
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
